package com.example.ai.chat.backend.controller;

import com.example.ai.chat.backend.entity.User;
import com.example.ai.chat.backend.repository.UserRepository;
import com.example.ai.chat.backend.dto.LoginRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/login")
    public ResponseEntity<Map<String, String>> login(@RequestBody LoginRequest loginRequest) {
        // 根据用户名查询用户
        User user = userRepository.findByUsername(loginRequest.getUsername())
                .orElseThrow(() -> new RuntimeException("用户名或密码错误"));

        // 验证密码（实际应用中应使用加密比对）
        if (!user.getPassword().equals(loginRequest.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 生成简单token（实际应用中应使用JWT等标准方案）
        String token = UUID.randomUUID().toString();

        // 返回用户信息和token
        Map<String, String> response = new HashMap<>();
        response.put("token", token);
        response.put("username", user.getUsername());
        response.put("nickname", user.getNickname());

        return ResponseEntity.ok(response);
    }
}